{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "2493fa7a-d19c-4a12-a563-b39c23e0c37a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "0\n",
    "corpus = [\n",
    "    \"这 是 第一个 文档\",\n",
    "    \"这是 第二个 文档\",\n",
    "    \"这是 最后 一个 文档\",\n",
    "    \"现在 没有 文档 了\"\n",
    "]\n",
    "\n",
    "## 手动实现\n",
    "words=[]\n",
    "\n",
    "for corpu in corpus:\n",
    "    words.extend(corpu.split())\n",
    "\n",
    "words = list(set(set(words)))\n",
    "\n",
    "word_dct={word:index for index,word in enumerate(words)}\n",
    "\n",
    "wocab_size=len(word_dct)\n",
    "\n",
    "def get_ont_hot(index):\n",
    "    one_hot=[0 for _ in range(wocab_size)]\n",
    "    one_hot[index]=1\n",
    "    return np.array(one_hot)\n",
    "\n",
    "\n",
    "indexs = [word_dct[word] for word in corpus[0].split()]\n",
    "\n",
    "[get_ont_hot(1) for index in indexs ]\n",
    "\n",
    "## 使用scikit-learn实现\n",
    "\n",
    "from sklearn.preprocessing import LabelBinarizer\n",
    "corpus[0]\n",
    "\n",
    "\n",
    "words\n",
    "\n",
    "lb = LabelBinarizer()\n",
    "lb.fit(words)\n",
    "lb.classes_\n",
    "\n",
    "sentence=corpus[0].split()\n",
    "\n",
    "one_hot=lb.transform(sentence)\n",
    "one_hot\n",
    "lb.inverse_transform(one_hot)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d7d9e88-c542-4d66-a291-cf3aff4b9865",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49d08f55-f8c1-47d5-a980-67e67a1d794a",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0523c9f4-24a2-4ed1-87bd-6a01b6ab823d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d847d00-3d2b-4743-9f16-97e75da398c3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93bebd3f-f245-4e03-9585-ac914cbecfea",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5561045f-88ba-48ec-bba2-564ad9e41d6c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbccc91a-8111-40a2-84c5-c6aeaa71df9b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
